//
//  WJNavigationController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/18.
//

import UIKit

class WJNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            
            appearance.configureWithOpaqueBackground()
            
            // 设置返回按钮颜色
            appearance.buttonAppearance.normal.titleTextAttributes = [
                .foregroundColor: UIColor.clear, // 设置返回文字颜色
                .font: UIFont.montserratMedium(16)
            ]
            
            // 设置返回按钮图标
            let backImage = UIImage(named: "nav_back")
            appearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .clear // 背景色
            appearance.shadowColor = .clear
            appearance.titleTextAttributes = [.foregroundColor: UIColor(hex: "#121212")] // 标题颜色
            
            // 应用到导航栏
            UINavigationBar.appearance().standardAppearance = appearance
            UINavigationBar.appearance().scrollEdgeAppearance = appearance // 适配滚动边缘场景
            UINavigationBar.appearance().tintColor = UIColor(hex: "#121212")
        } else {
            // iOS 13 以下版本
            UINavigationBar.appearance().barTintColor = .clear // 背景色
            UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor(hex: "#121212")] // 标题颜色
        }
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        setCustomTabBarHidden(false)
    }
}

extension UINavigationController {
    func popToViewController(ofType type: UIViewController.Type, animated: Bool) {
        // 查找栈中第一个匹配类型的控制器
        if let targetVC = viewControllers.first(where: { $0.isKind(of: type) }) {
            popToViewController(targetVC, animated: animated)
        } else {
            // 如果没有找到，可以创建新实例并重置堆栈
            let newVC = type.init()
            var newStack = viewControllers
            if let rootVC = newStack.first {
                newStack = [rootVC, newVC]
            } else {
                newStack = [newVC]
            }
            setViewControllers(newStack, animated: animated)
        }
    }
}
